<?php
// +----------------------------------------------------------------------
// | ThinkCMF [ WE CAN DO IT MORE SIMPLE ]
// +----------------------------------------------------------------------
// | Copyright (c) 2013-2014 http://www.thinkcmf.com All rights reserved.
// +----------------------------------------------------------------------
// | Author: Dean <zxxjjforever@163.com>
// +----------------------------------------------------------------------
namespace Portal\Controller;
use Common\Controller\HomebaseController; 
/**
 * 首页
 */
class IndexController extends HomebaseController {
	
    //首页
	public function index() {
	header("Location:index.php?m=Choose&a=index");
	
	}
	public function ind() {
		$timestamp = $_GET['timestamp'];
		$nonce      = $_GET['nonce'];
		$tocken     = 'BJfF3uCuNjCh4BeJ8Gfz';
		$signature  = $_GET['signature'];
		$array      = array($timestamp,$nonce ,$tocken);
		//1.字典序排序
		sort($array);
		//2.排序后的参数拼接成字符串用sha1加密
		$tmpstr = implode('',$array);
		$tmpstr = sha1( $tmpstr );
		//3.将加密后的字符串与signature比较，判断该请求是否来自于微信
		if( $tmpstr == $signature){
			echo $_GET['echostr'];
			exit();
		}
	}
	
	public function inde(){
		//1.获取code
		$appid="wxfbd889e62d33578b";
		$redirect_uri=urlencode("http://wx.028cube.com/yujia/index.php?m=Index&a=getUserOpenId");
		$url="https://open.weixin.qq.com/connect/oauth2/authorize?appid=".$appid."&redirect_uri=".$redirect_uri."&response_type=code&scope=snsapi_userinfo&state=123#wechat_redirect";
		header('Location:'.$url);
	}
	public function getUserOpenId(){
		//2.获取网页授权的access_token
		$appid="wxfbd889e62d33578b";
		$appsecret="02e677bc5da3d3f719eac3a626f5cc75";
		$code=$_GET['code'];
		$res=file_get_contents("https://api.weixin.qq.com/sns/oauth2/access_token?appid=".$appid."&secret=".$appsecret."&code=".$code."&grant_type=authorization_code");
		$res = json_decode($res,true);
		$access_token=$res['access_token'];
		$openid=$res['openid'];
		//3.拉取用户详细信息
		$url=file_get_contents("https://api.weixin.qq.com/sns/userinfo?access_token=".$access_token."&openid=".$openid."&lang=zh_CN");
		$res = json_decode($url,true);
		session(array('name'=>'session_id','expire'=>3600));
		$Member=M('member');
		if($openid){
			session('res',$res);
			$data['openid']=$openid;
			$uid=$Member->where($data)->getField('uid');
			if($uid){
				//该微信已注册（数据库有数据），将uid存入session
				session('uid',$uid);
			}else{
				$Member->startTrans();
				//该微信未注册，$data存入数据库，并将生成的uid存入session
				$data['nick']=urlencode($res['nickname']);
				$data['memberpic']=$res['headimgurl'];
				$data['sex']=$res['sex'];
				$data['age']=18;
				if($data['openid']){				
					$uid2=$Member->add($data);
				}
				session('uid',$uid2);
				if($uid2){
					$Member->commit();
				}else{
					$Member->rollback();
				}
			}
		}
		header("Location:index.php?m=Choose&a=index");
	}
}

